﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UIShare;
using EFong.View.Proxy;
using EFong.View.Customer;
using EFong.View.Base;

namespace EFong.View.HotelBooking
{
    public partial class Frm_HotelBooking : BasicMdiChildForm
    {
        private Proxy.BusinessServiceProxy _businessProxy { get { return Proxy.BusinessServiceProxy.GetInstance(); } }
        private Proxy.MasterServiceProxy _masterProxy { get { return Proxy.MasterServiceProxy.GetInstance(); } }

        public Frm_HotelBooking()
        {
            InitializeComponent();
            spe_BasePriceOrVendorDiscount.SetValue(null);
            spe_PrintTotalPrice.SetValue(null);

            rad_SCustomer.SetValue(false);
            rad_SOrderDate.SetValue(false);
            rad_SOrderRef.SetValue(false);
            rad_SVendor.SetValue(false);

            this.bbt_Void.Visibility = AppParameters.IsAdRole ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;
        }

        protected override void InitFields()
        {
        }

        protected override void Events()
        {
            this.gv_Orders.FocusedRowChanged += (s, e) =>
            {
                Contract.RHotelBooking hotelBooking = this.gv_Orders.GetRow(e.FocusedRowHandle) as Contract.RHotelBooking;

                if (hotelBooking != null)
                {
                    Order = _businessProxy.GetHotelBookingByID(hotelBooking.ID).ReturnValue;
                }
                else
                {
                    Order = null;
                }
            };

            this.gv_Details.FocusedRowChanged += (s, e) =>
            {
                Detail = this.gv_Details.GetRow(e.FocusedRowHandle) as Contract.HotelBookingDetail; ;
            };

            this.btn_CustomerData.Click += (s, e) =>
            {
                browserCustomerData();
            };
            this.btn_Search.Click += (s, e) =>
            {
                searchOrders();
            };
            this.btn_Clear.Click += (s, e) =>
            {
                clearSearchConditions();
            };
        }

        protected override void LoadDatas()
        {
            bds_Customer.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            bds_Vendor.BindingData(_masterProxy.GetAllHotelVendor().ReturnValue);

            //bds_hotelBooking.BindingData(new List<Contract.RHotelBooking>());

            clearSearchConditions();
            searchOrders();

            SetAuthorities();
        }

        protected void SetAuthorities()
        {
            foreach (Contract.RoleAuthorizedItem roleAuthorizedItem in AppParameters.LoginUser.Role.Authorities)
            {
                switch (roleAuthorizedItem.AuthorizedItem.Name)
                {
                    case "酒店预订":
                        bbt_Add.Enabled = roleAuthorizedItem.Allow;
                        bbt_Edit.Enabled = roleAuthorizedItem.Allow;
                        break;
                    case "高级修改":
                        bbt_Void.Enabled = roleAuthorizedItem.Allow;
                        break;
                }
            }
        }

        private void bar_Main_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "bbt_Add":
                    this.add();
                    break;
                case "bbt_Edit":
                    this.edit();
                    break;
                case "bbt_Void":
                    this.voidOrder();
                    break;
                case "bbt_Print":
                    this.printOrder();
                    break;
                case "bbt_Close":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        private void printOrder()
        {
            if (Order == null)
                return;

            BasicPrinterForm frm = new BasicPrinterForm();
            frm.Text = "打印订单";

            Print.Rpt_Hotel report = new Print.Rpt_Hotel();
            report.Order = Order;

            frm.Report = report;

            FormOpener.ShowDialog(frm);
        }

        private void voidOrder()
        {
            bool isSure = false;
            MsgBox.Question("确定将订单作废?", () => { isSure = true; }, null);
            if (!isSure)
                return;

            if (Order == null)
                return;

            Frm_Void frm = new Frm_Void(Order);
            frm.Text = "订单作废";
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                searchOrders();
            }
        }

        private void add()
        {
            Frm_HotelBookingEdit frm = new Frm_HotelBookingEdit();
            frm.Text = "增加订单";
            frm.ViewState = ViewStates.ADD;
            frm.Load += (s, e) =>
                {
                    frm.Order = new Contract.HotelBooking();
                };
            FormOpener.ShowDialog(frm);

            if (frm.ReturnValue != null && this.bds_hotelBooking.DataSource is List<Contract.RHotelBooking>)
            {
                this.bds_hotelBooking.Insert(0, frm.ReturnValue);
            }
        }

        private void edit()
        {
            if (Order == null)
                return;
            if (Order.Status == MsgResource.VoidStatus)
                return;

            Frm_HotelBookingEdit frm = new Frm_HotelBookingEdit();
            frm.Text = "修改订单资料";
            frm.ViewState = ViewStates.EDIT;
            frm.Load += (s, e) =>
                {
                    frm.Order = Order;
                };
            if (FormOpener.ShowDialog(frm) == DialogResult.OK)
            {
                this.gv_Orders.BeginUpdate();
                this.gv_Orders.EndUpdate();
                Order = frm.Order;
            }
        }


        private void browserCustomerData()
        {
            if (Order == null)
                return;

            Frm_CustomerEdit frm = new Frm_CustomerEdit();
            frm.Text = "客户详细资料";
            frm.ViewState = ViewStates.BROWSER;
            frm.Load += (s, e) =>
            {
                frm.CurCust = Order.Customer;
            };
            FormOpener.ShowDialog(frm);
        }

        private void searchOrders()
        {
            List<Contract.RHotelBooking> hotelBokkingSource = new List<Contract.RHotelBooking>();

            if (rad_SCustomer.Checked)
            {
                hotelBokkingSource = _businessProxy.GetHotelBookingByCustomer(this.cmb_SearchCustomer.GetValue() as Contract.RCustomer).ReturnValue;
            }
            else if (rad_SOrderDate.Checked)
            {
                hotelBokkingSource = _businessProxy.GetHotelBookingByOrderDate(this.dte_SearchStartDate.GetValue(AppParameters.FetureDateTime), this.dte_SearchEndDate.GetValue(AppParameters.FetureDateTime).AddDays(1)).ReturnValue;
            }
            else if (rad_SOrderRef.Checked)
            {
                hotelBokkingSource = _businessProxy.GetHotelBookingByRef(this.txt_SearchOrderRef.GetText()).ReturnValue;
            }
            else if (rad_SVendor.Checked)
            {
                hotelBokkingSource = _businessProxy.GetHotelBookingByVendor(this.cmb_SearchVendor.GetValue() as Contract.RVendor).ReturnValue;
            }
            else if (rad_GuestName.Checked)
            {
                hotelBokkingSource = _businessProxy.GetHotelBookingByGuestName(this.txt_SearchGuestName.GetText()).ReturnValue;
            }
            else 
            {
                hotelBokkingSource = _businessProxy.GetAllHotelBooking().ReturnValue;
            }
            bool sourceIsNull = hotelBokkingSource == null;
            bool sourceIsEmpty = !sourceIsNull && hotelBokkingSource.Count == 0;

            if (sourceIsEmpty)
            {
                MsgBox.Info("没有找到符合条件的订单.");
                this.Order = null;
                this.bds_hotelBooking.BindingData(new List<Contract.OtherBusiness>());
            }
            else
            {
                foreach (var order in hotelBokkingSource)
                {
                    if (order.Status == "已作废") 
                        order.CustomerStatus = "已作废";
                }

                this.bds_hotelBooking.BindingData(hotelBokkingSource);
            }
        }

        private void clearSearchConditions()
        {
            this.rad_SCustomer.SetValue(false);
            this.rad_SOrderDate.SetValue(false);
            this.rad_SOrderRef.SetValue(false);
            this.rad_SVendor.SetValue(false);
            ControlExtensions.ClearValue(
                this.cmb_SearchCustomer,
                this.cmb_SearchVendor,
                this.dte_SearchEndDate,
                this.dte_SearchStartDate,
                this.txt_SearchOrderRef
                );

            //var hotelBookingList = _businessProxy.GetAllHotelBooking();
            //if (hotelBookingList.IsSuccess)
            //    this.bds_hotelBooking.BindingData(hotelBookingList.ReturnValue);
        }

        #region Order
        //selected hotel booking
        private Contract.HotelBooking _order;
        public Contract.HotelBooking Order
        {
            get { return _order; }
            set
            {
                _order = value;
                onOrderChanged();
            }
        }

        private void onOrderChanged()
        {
            if (Order == null)
            {
                ControlExtensions.ClearValue(
                    this.txtAddress,
                    this.txt_OrderUser,
                    this.dte_OrderDate,
                    this.txt_OrderRef,
                    this.txt_Customer,
                    this.txt_Vendor,
                    this.txt_OrderTicketUser,
                    this.txt_CustomerPaymentType,
                    this.txt_VendorCurrency,
                    this.spe_ExchangeRate,
                    this.spe_PrintTotalPrice,
                    this.txt_OrderRemark,
                    //this.txt_PaymentType,
                    //this.txt_BankAccount,
                    this.txt_VendorCurrency,
                    this.txt_OrderTotalPrice,
                    this.txt_OrderTotalProfit,
                    this.txt_OrderTotalVendorPrice,
                    this.txt_OrderTotalIntegralExchange,
                    this.txt_ProvideTicketUser,
                    this.dte_DeliveryTicketDate,
                    this.dte_ProvideTicketDate,
                    this.txt_CPerson,
                    this.txt_CPersonPhone,
                    this.txt_CPersonTel
                    );
                this.bds_hotelBookingDetail.BindingData(null);
            }
            else
            {
                foreach (var detail in Order.Details)
                {
                    detail.HotelBooking = Order;
                }

                this.txtAddress.SetText(Order.Address);
                this.txt_OrderUser.SetText(Order.OrderUser);
                this.dte_OrderDate.SetValue(Order.OrderDate);
                this.txt_OrderRef.SetText(Order.Ref);
                this.txt_Customer.SetText(Order.Customer);
                this.txt_Vendor.SetText(Order.Vendor);
                this.txt_OrderTicketUser.SetText(Order.OrderHotelUser);
                this.txt_CustomerPaymentType.SetText(Order.CustomerPaymentType);
                this.txt_VendorCurrency.SetText(Order.VendorCurrency);
                this.spe_ExchangeRate.SetValue(Order.ExchangeRate);
                this.spe_PrintTotalPrice.SetValue(Order.PrintTotalPrice);
                this.txt_OrderRemark.SetText(Order.Remark);

                this.txt_CPerson.SetText(Order.ContactPerson);
                this.txt_CPersonTel.SetText(Order.联系电话);
                this.txt_CPersonPhone.SetText(Order.移动电话);

                this.txt_ProvideTicketUser.SetText(Order.ProvideTicketUser);
                this.dte_DeliveryTicketDate.SetValue(Order.DeliveryDate);
                this.dte_ProvideTicketDate.SetValue(Order.ProvideTicketDate);

                //txt_PaymentType.SetText(Order.PaymentType);
                //txt_BankAccount.SetText(Order.BankAccount);
                if (Order.VendorCurrency != null)
                    this.txt_VendorCurrency.SetText(Order.VendorCurrency);

                this.txt_OrderTotalPrice.SetText(Order.TotalPrice);
                this.txt_OrderTotalProfit.SetText(Order.TotalProfit);
                this.txt_OrderTotalVendorPrice.SetText(Order.TotalVendorPrice);
                this.txt_OrderTotalIntegralExchange.SetText(Order.TotalIntergral);

                this.bds_hotelBookingDetail.BindingData(Order.Details);
            }
        }
        #endregion

        #region Detail
        private Contract.HotelBookingDetail _detail;
        public Contract.HotelBookingDetail Detail
        {
            get { return _detail; }
            set
            {
                _detail = value;
                onDetailChanged();
            }
        }

        private void onDetailChanged()
        {
            if (Detail == null)
            {
                ControlExtensions.ClearValue(
                    dte_CheckInDate,
                    dte_CheckOutDate,
                    txt_GuestName,
                    txt_ConfirmationRef,
                    txt_HotelName,
                    txt_HotelOrderRef,
                    spe_HotelTax,
                    spe_Price,
                    txt_HotelLevel,
                    spe_Rooms,
                    txt_RoomType,
                    txt_TotalIntegralExchange,
                    txt_TotalPrice,
                    txt_TotalProfit,
                    txt_TotalVendorPrice);
            }
            else
            {
                this.dte_CheckInDate.SetValue(Detail.CheckInDate);
                this.dte_CheckOutDate.SetValue(Detail.CheckOutDate);
                this.txt_GuestName.SetText(Detail.GuestName);
                this.txt_ConfirmationRef.SetText(Detail.HotelConfirmationRef);
                this.txt_HotelName.SetText(Detail.HotelName);
                this.txt_HotelOrderRef.SetText(Detail.HotelOrderRef);
                this.spe_HotelTax.SetValue(Detail.HotelTax);
                this.spe_Price.SetValue(Detail.Price);
                this.txt_HotelLevel.SetText(Detail.HotelLeave);
                this.spe_Rooms.SetValue(Detail.Rooms);
                this.txt_RoomType.SetText(Detail.RoomType);

                if (Detail.VendorDiscount.HasValue)
                {
                    this.rad_VendorDiscount.Checked = true;
                    this.spe_BasePriceOrVendorDiscount.SetValue(Detail.VendorDiscount);
                }
                else if (Detail.VendorPrice.HasValue)
                {
                    this.rad_BasePrice.Checked = true;
                    this.spe_BasePriceOrVendorDiscount.SetValue(Detail.VendorPrice);
                }
                else
                {
                    this.rad_BasePrice.Checked = this.rad_VendorDiscount.Checked = false;
                    this.spe_BasePriceOrVendorDiscount.SetValue(null);
                }

                this.spe_Days.SetValue(Detail.Days);
                this.txt_TotalPrice.SetText(Detail.TotalPrice);
                this.txt_TotalProfit.SetText(Detail.Profit);
                this.txt_TotalVendorPrice.SetText(Detail.TotalVendorPrice);
                this.txt_TotalIntegralExchange.SetText(Detail.Intergral);
            }
        }
        #endregion
    }
}
